﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHModel.Entities;
using NHibernate;

namespace NHBLL
{
    public static class UserInfoService
    {
        public static IList<UserInfo> GetAll()
        {
            ISession session = NHelper.GetCurrentSession();
            IQuery iq = session.CreateQuery("from UserInfo");
            return iq.List<UserInfo>();
        }

        public static bool Add(UserInfo u)
        {
            ISession session = NHelper.GetCurrentSession();
            ITransaction it = session.BeginTransaction();
            bool flag = true;
            try
            {
                session.Save(u);
                it.Commit();
            }
            catch (Exception ex)
            {
                flag = false;
                it.Rollback();
                throw (ex);
            }
            return flag;
        }

        public static UserInfo GetModelByUserName(string UserName)
        {
            ISession session = NHelper.GetCurrentSession();
            ICriteria crit = session.CreateCriteria(typeof(UserInfo));
            crit.Add(NHibernate.Criterion.Expression.Eq("UserName", UserName));
            UserInfo item = (UserInfo)crit.UniqueResult();
            return item;    
        }

        public static bool Update(object obj)
        {
            bool flag = true;
            ISession session = NHelper.GetCurrentSession();

            ITransaction it = session.BeginTransaction();
            try
            {
                session.Update(obj);
                it.Commit();
            }
            catch (Exception)
            {
                flag = false;
                it.Rollback();
                throw;
            }
            session.Flush();
            return flag;
        }

        public static bool Delete()
        {
            bool flag = true;
            ISession session = NHelper.GetCurrentSession();
            ITransaction it = session.BeginTransaction();
            try
            {
                IQuery iq = session.CreateSQLQuery("delete from UserInfo where UserName=:a");
                iq.SetParameter("a", "Andy");
                iq.ExecuteUpdate();
                it.Commit();
            }
            catch (Exception)
            {
                flag = false;
                it.Rollback();
                throw;
            }
            session.Flush();
            return flag;
        }
    }
}
